package com.jianyun.jyzs.activity;

import android.annotation.SuppressLint;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.jianyun.jyzs.R;
import com.jianyun.jyzs.adapter.CrmSignCalendarAdapter;
import com.jianyun.jyzs.adapter.TripSignAdapter;
import com.jianyun.jyzs.bean.CrmSignDB;
import com.jianyun.jyzs.bean.DateInfo;
import com.jianyun.jyzs.bean.DateInfo2;
import com.jianyun.jyzs.constant.SysConstant;
import com.jianyun.jyzs.dao.CrmSignDao;
import com.jianyun.jyzs.utils.LoginCache;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import com.jianyun.jyzs.utils.RceLog;
import com.jianyun.jyzs.utils.UtilsStyle;

/**
 * Created by yangshijun on 2018/6/4.
 */

public class CrmSignCalendarActivity extends AppCompatActivity {
    @BindView(R.id.topBack)
    ImageView topBack;
    @BindView(R.id.topText)
    TextView topText;
    @BindView(R.id.tv_checked)
    TextView tvChecked;
    @BindView(R.id.tv_update)
    TextView tvUpdate;
    @BindView(R.id.iv_more)
    ImageView ivMore;
    @BindView(R.id.iv_moreLinearLayout)
    LinearLayout ivMoreLinearLayout;
    @BindView(R.id.topCreat)
    LinearLayout topCreat;
    @BindView(R.id.iv_single)
    ImageView ivSingle;
    @BindView(R.id.iv_group)
    ImageView ivGroup;
    @BindView(R.id.topChatDetail)
    LinearLayout topChatDetail;
    @BindView(R.id.topId)
    RelativeLayout topId;
    @BindView(R.id.left_img)
    TextView leftImg;
    @BindView(R.id.btn_prev_month)
    LinearLayout btnPrevMonth;
    @BindView(R.id.tv_month)
    TextView tvMonth;
    @BindView(R.id.right_img)
    TextView rightImg;
    @BindView(R.id.btn_next_month)
    LinearLayout btnNextMonth;
    @BindView(R.id.calendar)
    RecyclerView calendarRecycler;
    @BindView(R.id.loadButton)
    Button loadButton;
    @BindView(R.id.nullLinearLayout)
    LinearLayout nullLinearLayout;
    @BindView(R.id.orderList)
    RecyclerView orderList;


    private SimpleDateFormat yyyy_mm_dd;
    private CrmSignDao orderDao;
    private Calendar calendar;
    private TripSignAdapter orderAdapter;

    private List<List<CrmSignDB>> calendarData = new ArrayList<>();
    private ArrayList<DateInfo2> dateList;
    private CrmSignCalendarAdapter calendarAdapter;
    private String crmid;
    private String userId;
    private String enterpriseCode;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        UtilsStyle.setStatusBarMode(this,true);
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_order_calendar);
        ButterKnife.bind(this);
        initData();
    }

    private void initData() {
        crmid = getIntent().getStringExtra(SysConstant.msg_key_string1);
        userId = LoginCache.getInstance().getUserInfo().getUserId();
        enterpriseCode = LoginCache.getInstance().getLoginCache().getEnterpriseCode();
        yyyy_mm_dd = new SimpleDateFormat("yyyy_MM_dd");
        orderDao = new CrmSignDao(this);
        calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        orderAdapter = new TripSignAdapter(this, null);
        orderList.setLayoutManager(new LinearLayoutManager(this));
        orderList.setAdapter(orderAdapter);
        List<CrmSignDB> all = orderDao.getAll();
        RceLog.d("lml","全部数据"+all.toString());
        initCalendar(calendar);
        initView();
    }

    @OnClick({R.id.topBack, R.id.btn_prev_month, R.id.btn_next_month})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.btn_prev_month:
                calendar.add(Calendar.MONTH,-1);
                initCalendar(calendar);
                calendarAdapter.setList(dateList);
                break;
            case R.id.btn_next_month:
                calendar.add(Calendar.MONTH,1);
                initCalendar(calendar);
                calendarAdapter.setList(dateList);
                break;
            case R.id.topBack:
                finish();
                break;
        }
    }

    @SuppressLint("WrongConstant")
    private void initCalendar(Calendar calendar) {
        calendarData.clear();
        dateList = new ArrayList<>();
        int year = calendar.get(Calendar.YEAR);
        String year_ = year + "";
        int month = calendar.get(Calendar.MONTH) + 1;
        String month_ = (month + "").length() > 1 ? (month + "") : "0" + month;
        tvMonth.setText(year + "年" + month + "月");
        String format = year_ + "/" + month_ + "/";
        int maxDay = calendar.getActualMaximum(Calendar.DAY_OF_MONTH);//获得当前日期所在月份有多少天（或者说day的最大值)，用于后面的计算
        for (int i = 0; i < maxDay; i++) {
            int d = i + 1;
            String day_ =  d+"";
            calendarData.add(orderDao.getCrmSignDate(crmid,userId, enterpriseCode, format + day_));
        }
        Calendar calendarClone = (Calendar) calendar.clone(); //克隆一个Calendar再进行操作，避免造成混乱
        calendarClone.set(Calendar.DAY_OF_MONTH, 1);  //将日期调到当前月份的第一天
        int startDayOfWeek = calendarClone.get(Calendar.DAY_OF_WEEK); //获得当前日期所在月份的第一天是星期几
        calendarClone.set(Calendar.DAY_OF_MONTH, maxDay); //将日期调到当前月份的最后一天
        int endDayOfWeek = calendarClone.get(Calendar.DAY_OF_WEEK); //获得当前日期所在月份的最后一天是星期几

        //计算上一个月在本月日历页出现的那几天.
        //比如，startDayOfWeek = 3，表示当月第一天是星期二，所以日历向前会空出2天的位置，那么让上月的最后两天显示在星期日和星期一的位置上.
        int startEmptyCount = startDayOfWeek - 1; //上月在本月日历页因该出现的天数。
        Calendar preCalendar = (Calendar) calendar.clone();  //克隆一份再操作
        preCalendar.set(Calendar.DAY_OF_MONTH, 1); //将日期调到当月第一天
        preCalendar.add(Calendar.DAY_OF_MONTH, -startEmptyCount); //向前推移startEmptyCount天
        for (int i = 0; i < startEmptyCount; i++) {
            DateInfo2 dateInfo = new DateInfo2(); //使用DateInfo来储存所需的相关信息
            dateInfo.setDate(preCalendar.getTime());
            dateInfo.setDayOfM(preCalendar.get(Calendar.DAY_OF_MONTH));
            dateInfo.setType(DateInfo.PRE_MONTH); //标记日期信息的类型为上个月
            dateList.add(dateInfo); //将日期添加到数组中
            preCalendar.add(Calendar.DAY_OF_MONTH, 1); //向后推移一天
        }
        /**
         * 计算当月的每一天日期
         */
        calendar.set(Calendar.DAY_OF_MONTH, 1); //由于是获取当月日期信息，所以直接操作当月Calendar即可。将日期调为当月第一天
        for (int i = 0; i < maxDay; i++) {
            DateInfo2 dateInfo = new DateInfo2();
            dateInfo.setDate(calendar.getTime());
            dateInfo.setCrms(calendarData.get(i));
            dateInfo.setDayOfM(calendar.get(Calendar.DAY_OF_MONTH));
            dateInfo.setType(DateInfo.CURRENT_MONTH);  //标记日期信息的类型为当月
            dateList.add(dateInfo);
            dateInfo.setToday(isToday(calendar.getTime()));
            calendar.add(Calendar.DAY_OF_MONTH, 1); //向后推移一天

        }



        /**
         * 计算下月在本月日历页出现的那几天。
         * 比如，endDayOfWeek = 6，表示当月第二天是星期五，所以日历向后会空出1天的位置，那么让下月的第一天显示在星期六的位置上。
         */
        int endEmptyCount = 7 - endDayOfWeek; //下月在本月日历页上因该出现的天数
        Calendar afterCalendar = (Calendar) calendar.clone(); //同样，克隆一份在操作
        for (int i = 0; i < endEmptyCount; i++) {
            DateInfo2 dateInfo = new DateInfo2();
            dateInfo.setDate(afterCalendar.getTime());
            dateInfo.setDayOfM(afterCalendar.get(Calendar.DAY_OF_MONTH));
            dateInfo.setType(DateInfo.AFTER_MONTH); //将DateInfo类型标记为下个月
            dateList.add(dateInfo);
            afterCalendar.add(Calendar.DAY_OF_MONTH, 1); //向后推移一天
        }
        this.calendar.add(Calendar.MONTH,-1);
    }
    private boolean isToday(Date date) {
        String format = yyyy_mm_dd.format(date);
        String format1 = yyyy_mm_dd.format(new Date());
        if (format.equals(format1)) {
            return true;
        } else {
            return false;
        }

    }

    private void initView() {
        topBack.setVisibility(View.VISIBLE);
        topText.setText("出差签到记录");
        calendarRecycler.setLayoutManager(new GridLayoutManager(this, 7));
        calendarAdapter = new CrmSignCalendarAdapter(this, dateList);
        calendarRecycler.setAdapter(calendarAdapter);
        String today = new SimpleDateFormat("yyyy/MM/dd").format(new Date());
        List<CrmSignDB> workOrder = orderDao.getCrmSignDate(crmid,userId, enterpriseCode, today);

        setOrderView(workOrder);
    }

    public void setOrderView(List<CrmSignDB> orders) {
        if (orders != null & orders.size() > 0) {
            orderAdapter.setList(orders);
            nullLinearLayout.setVisibility(View.GONE);
        } else {
            orderAdapter.setList(null);
            nullLinearLayout.setVisibility(View.VISIBLE);
        }

    }
}
